{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Transforms and Resampling <a href=\"https://mybinder.org/v2/gh/InsightSoftwareConsortium/SimpleITK-Notebooks/master?filepath=Python%2F21_Transforms_and_Resampling.ipynb\"><img style=\"float: right;\" src=\"https://mybinder.org/badge_logo.svg\"></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook explains how to apply transforms to images, and how to perform image resampling."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import SimpleITK as sitk\n",
    "import numpy as np\n",
    "import itertools\n",
    "\n",
    "%matplotlib inline\n",
    "import gui\n",
    "from matplotlib import pyplot as plt\n",
    "from ipywidgets import interact, fixed\n",
    "\n",
    "# Utility method that either downloads data from the Girder repository or\n",
    "# if already downloaded returns the file name for reading from disk (cached data).\n",
    "%run update_path_to_download_script\n",
    "from downloaddata import fetch_data as fdata"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating and Manipulating Transforms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A number of different spatial transforms are available in SimpleITK.\n",
    "\n",
    "The simplest is the Identity Transform.  This transform simply returns input points unaltered."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dimension = 2\n",
    "\n",
    "print(\"*Identity Transform*\")\n",
    "identity = sitk.Transform(dimension, sitk.sitkIdentity)\n",
    "print(\"Dimension: \" + str(identity.GetDimension()))\n",
    "\n",
    "# Points are always defined in physical space\n",
    "point = (1.0, 1.0)\n",
    "\n",
    "\n",
    "def transform_point(transform, point):\n",
    "    transformed_point = transform.TransformPoint(point)\n",
    "    print(\"Point \" + str(point) + \" transformed is \" + str(transformed_point))\n",
    "\n",
    "\n",
    "transform_point(identity, point)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Transform are defined by two sets of parameters, the *Parameters* and *FixedParameters*.  *FixedParameters* are not changed during the optimization process when performing registration.  For the TranslationTransform, the Parameters are the values of the translation Offset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"*Translation Transform*\")\n",
    "translation = sitk.TranslationTransform(dimension)\n",
    "\n",
    "print(\"Parameters: \" + str(translation.GetParameters()))\n",
    "print(\"Offset:     \" + str(translation.GetOffset()))\n",
    "print(\"FixedParameters: \" + str(translation.GetFixedParameters()))\n",
    "transform_point(translation, point)\n",
    "\n",
    "print(\"\")\n",
    "translation.SetParameters((3.1, 4.4))\n",
    "print(\"Parameters: \" + str(translation.GetParameters()))\n",
    "transform_point(translation, point)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The affine transform is capable of representing translations, rotations, shearing, and scaling."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"*Affine Transform*\")\n",
    "affine = sitk.AffineTransform(dimension)\n",
    "\n",
    "print(\"Parameters: \" + str(affine.GetParameters()))\n",
    "print(\"FixedParameters: \" + str(affine.GetFixedParameters()))\n",
    "transform_point(affine, point)\n",
    "\n",
    "print(\"\")\n",
    "affine.SetTranslation((3.1, 4.4))\n",
    "print(\"Parameters: \" + str(affine.GetParameters()))\n",
    "transform_point(affine, point)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A number of other transforms exist to represent non-affine deformations, well-behaved rotation in 3D, etc. See the [Transforms](22_Transforms.ipynb) tutorial for more information."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Applying Transforms to Images"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create a function to display the images that is aware of image spacing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def myshow(img, title=None, margin=0.05, dpi=80):\n",
    "    nda = sitk.GetArrayViewFromImage(img)\n",
    "    spacing = img.GetSpacing()\n",
    "\n",
    "    ysize = nda.shape[0]\n",
    "    xsize = nda.shape[1]\n",
    "\n",
    "    figsize = (1 + margin) * ysize / dpi, (1 + margin) * xsize / dpi\n",
    "\n",
    "    fig = plt.figure(title, figsize=figsize, dpi=dpi)\n",
    "    ax = fig.add_axes([margin, margin, 1 - 2 * margin, 1 - 2 * margin])\n",
    "\n",
    "    extent = (0, xsize * spacing[1], 0, ysize * spacing[0])\n",
    "\n",
    "    t = ax.imshow(\n",
    "        nda, extent=extent, interpolation=\"hamming\", cmap=\"gray\", origin=\"lower\"\n",
    "    )\n",
    "\n",
    "    if title:\n",
    "        plt.title(title)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create a grid image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grid = sitk.GridSource(\n",
    "    outputPixelType=sitk.sitkUInt16,\n",
    "    size=(250, 250),\n",
    "    sigma=(0.5, 0.5),\n",
    "    gridSpacing=(5.0, 5.0),\n",
    "    gridOffset=(0.0, 0.0),\n",
    "    spacing=(0.2, 0.2),\n",
    ")\n",
    "myshow(grid, \"Grid Input\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To apply the transform, a resampling operation is required."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def resample(image, transform):\n",
    "    # Output image Origin, Spacing, Size, Direction are taken from the reference\n",
    "    # image in this call to Resample\n",
    "    reference_image = image\n",
    "    interpolator = sitk.sitkCosineWindowedSinc\n",
    "    default_value = 100.0\n",
    "    return sitk.Resample(image, reference_image, transform, interpolator, default_value)\n",
    "\n",
    "\n",
    "translation.SetOffset((3.1, 4.6))\n",
    "transform_point(translation, point)\n",
    "resampled = resample(grid, translation)\n",
    "myshow(resampled, \"Resampled Translation\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What happened?  The translation is positive in both directions.  Why does the output image move down and to the left?  It important to keep in mind that a transform in a resampling operation defines *the transform from the output space to the input space*."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "translation.SetOffset(-1 * np.array(translation.GetParameters()))\n",
    "transform_point(translation, point)\n",
    "resampled = resample(grid, translation)\n",
    "myshow(resampled, \"Inverse Resampled\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An affine (line preserving) transformation, can perform translation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "def affine_translate(transform, x_translation=3.1, y_translation=4.6):\n",
    "    new_transform = sitk.AffineTransform(transform)\n",
    "    new_transform.SetTranslation((x_translation, y_translation))\n",
    "    resampled = resample(grid, new_transform)\n",
    "    myshow(resampled, \"Translated\")\n",
    "    return new_transform\n",
    "\n",
    "\n",
    "affine = sitk.AffineTransform(dimension)\n",
    "\n",
    "interact(\n",
    "    affine_translate,\n",
    "    transform=fixed(affine),\n",
    "    x_translation=(-5.0, 5.0),\n",
    "    y_translation=(-5.0, 5.0),\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "or scaling:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def affine_scale(transform, x_scale=3.0, y_scale=0.7):\n",
    "    new_transform = sitk.AffineTransform(transform)\n",
    "    matrix = np.array(transform.GetMatrix()).reshape((dimension, dimension))\n",
    "    matrix[0, 0] = x_scale\n",
    "    matrix[1, 1] = y_scale\n",
    "    new_transform.SetMatrix(matrix.ravel())\n",
    "    resampled = resample(grid, new_transform)\n",
    "    myshow(resampled, \"Scaled\")\n",
    "    print(matrix)\n",
    "    return new_transform\n",
    "\n",
    "\n",
    "affine = sitk.AffineTransform(dimension)\n",
    "\n",
    "interact(affine_scale, transform=fixed(affine), x_scale=(0.2, 5.0), y_scale=(0.2, 5.0));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "or rotation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def affine_rotate(transform, degrees=15.0):\n",
    "    parameters = np.array(transform.GetParameters())\n",
    "    new_transform = sitk.AffineTransform(transform)\n",
    "    matrix = np.array(transform.GetMatrix()).reshape((dimension, dimension))\n",
    "    radians = -np.pi * degrees / 180.0\n",
    "    rotation = np.array(\n",
    "        [[np.cos(radians), -np.sin(radians)], [np.sin(radians), np.cos(radians)]]\n",
    "    )\n",
    "    new_matrix = np.dot(rotation, matrix)\n",
    "    new_transform.SetMatrix(new_matrix.ravel())\n",
    "    resampled = resample(grid, new_transform)\n",
    "    print(new_matrix)\n",
    "    myshow(resampled, \"Rotated\")\n",
    "    return new_transform\n",
    "\n",
    "\n",
    "affine = sitk.AffineTransform(dimension)\n",
    "\n",
    "interact(affine_rotate, transform=fixed(affine), degrees=(-90.0, 90.0));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "or shearing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "def affine_shear(transform, x_shear=0.3, y_shear=0.1):\n",
    "    new_transform = sitk.AffineTransform(transform)\n",
    "    matrix = np.array(transform.GetMatrix()).reshape((dimension, dimension))\n",
    "    matrix[0, 1] = -x_shear\n",
    "    matrix[1, 0] = -y_shear\n",
    "    new_transform.SetMatrix(matrix.ravel())\n",
    "    resampled = resample(grid, new_transform)\n",
    "    myshow(resampled, \"Sheared\")\n",
    "    print(matrix)\n",
    "    return new_transform\n",
    "\n",
    "\n",
    "affine = sitk.AffineTransform(dimension)\n",
    "\n",
    "interact(affine_shear, transform=fixed(affine), x_shear=(0.1, 2.0), y_shear=(0.1, 2.0));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Composite Transform"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is possible to compose multiple transform together into a single transform object.  With a composite transform, multiple resampling operations are prevented, so interpolation errors are not accumulated.  For example, an affine transformation that consists of a translation and rotation,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "translate = (8.0, 16.0)\n",
    "rotate = 20.0\n",
    "\n",
    "affine = sitk.AffineTransform(dimension)\n",
    "affine = affine_translate(affine, translate[0], translate[1])\n",
    "affine = affine_rotate(affine, rotate)\n",
    "\n",
    "resampled = resample(grid, affine)\n",
    "myshow(resampled, \"Single Transform\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "can also be represented with two Transform objects applied in sequence with a Composite Transform,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "composite = sitk.CompositeTransform(dimension)\n",
    "translation = sitk.TranslationTransform(dimension)\n",
    "translation.SetOffset(-1 * np.array(translate))\n",
    "composite.AddTransform(translation)\n",
    "affine = sitk.AffineTransform(dimension)\n",
    "affine = affine_rotate(affine, rotate)\n",
    "\n",
    "composite.AddTransform(translation)\n",
    "composite = sitk.CompositeTransform(dimension)\n",
    "composite.AddTransform(affine)\n",
    "\n",
    "resampled = resample(grid, composite)\n",
    "myshow(resampled, \"Two Transforms\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Beware*, transforms are non-commutative -- order matters!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "composite = sitk.CompositeTransform(dimension)\n",
    "composite.AddTransform(affine)\n",
    "composite.AddTransform(translation)\n",
    "\n",
    "resampled = resample(grid, composite)\n",
    "myshow(resampled, \"Composite transform in reverse order\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Resampling\n",
    "\n",
    "<img src=\"resampling.svg\"/><br><br>\n",
    "\n",
    "Resampling as the verb implies is the action of sampling an image, which itself is a sampling of an original continuous signal.\n",
    "\n",
    "Generally speaking, resampling in SimpleITK involves four components:\n",
    "1. Image - the image we resample, given in coordinate system $m$.\n",
    "2. Resampling grid - a regular grid of points given in coordinate system $f$ which will be mapped to coordinate system $m$.\n",
    "2. Transformation $T_f^m$ - maps points from coordinate system $f$ to coordinate system $m$, $^mp = T_f^m(^fp)$.\n",
    "3. Interpolator - method for obtaining the intensity values at arbitrary points in coordinate system $m$ from the values of the points defined by the Image.\n",
    "\n",
    "\n",
    "While SimpleITK provides a large number of interpolation methods, the two most commonly used are ```sitkLinear``` and ```sitkNearestNeighbor```. The former is used for most interpolation tasks, a compromise between accuracy and computational efficiency. The later is used to interpolate labeled images representing a segmentation as it does not introduce new labels into the result.\n",
    "\n",
    "SimpleITK's procedural API provides three methods for performing resampling, with the difference being the way you specify the resampling grid:\n",
    "\n",
    "1. ```Resample(const Image &image1, Transform transform, InterpolatorEnum interpolator, double defaultPixelValue, PixelIDValueEnum outputPixelType)```\n",
    "2. ```Resample(const Image &image1, const Image &referenceImage, Transform transform, InterpolatorEnum interpolator, double defaultPixelValue, PixelIDValueEnum outputPixelType)```\n",
    "3. ```Resample(const Image &image1, std::vector< uint32_t > size, Transform transform, InterpolatorEnum interpolator, std::vector< double > outputOrigin, std::vector< double > outputSpacing, std::vector< double > outputDirection, double defaultPixelValue, PixelIDValueEnum outputPixelType)```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def resample_display(image, euler2d_transform, tx, ty, theta):\n",
    "    euler2d_transform.SetTranslation((tx, ty))\n",
    "    euler2d_transform.SetAngle(theta)\n",
    "\n",
    "    resampled_image = sitk.Resample(image, euler2d_transform)\n",
    "    plt.imshow(sitk.GetArrayFromImage(resampled_image))\n",
    "    plt.axis(\"off\")\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "logo = sitk.ReadImage(fdata(\"SimpleITK.jpg\"))\n",
    "\n",
    "euler2d = sitk.Euler2DTransform()\n",
    "# Why do we set the center?\n",
    "euler2d.SetCenter(\n",
    "    logo.TransformContinuousIndexToPhysicalPoint(np.array(logo.GetSize()) / 2.0)\n",
    ")\n",
    "interact(\n",
    "    resample_display,\n",
    "    image=fixed(logo),\n",
    "    euler2d_transform=fixed(euler2d),\n",
    "    tx=(-128.0, 128.0, 2.5),\n",
    "    ty=(-64.0, 64.0),\n",
    "    theta=(-np.pi / 4.0, np.pi / 4.0),\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Common Errors\n",
    "\n",
    "It is not uncommon to end up with an empty (all black) image after resampling. This is due to:\n",
    "1. Using wrong settings for the resampling grid, not too common, but does happen.\n",
    "2. Using the inverse of the transformation $T_f^m$. This is a relatively common error, which is readily addressed by invoking the transformations ```GetInverse``` method."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Defining the Resampling Grid\n",
    "\n",
    "In the example above we arbitrarily used the original image grid as the resampling grid. As a result, for many of the transformations the resulting image contained black pixels, pixels which were mapped outside the spatial domain of the original image and a partial view of the original image.\n",
    "\n",
    "If we want the resulting image to contain all of the original image no matter the transformation, we will need to define the resampling grid using our knowledge of the original image's spatial domain and the **inverse** of the given transformation. \n",
    "\n",
    "Computing the bounds of the resampling grid when dealing with an affine transformation is straightforward. An affine transformation preserves convexity with extreme points mapped to extreme points. Thus we only need to apply the **inverse** transformation to the corners of the original image to obtain the bounds of the resampling grid.\n",
    "\n",
    "Computing the bounds of the resampling grid when dealing with a BSplineTransform or DisplacementFieldTransform is more involved as we are not guaranteed that extreme points are mapped to extreme points. This requires that we apply the **inverse** transformation to all points in the original image to obtain the bounds of the resampling grid.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "euler2d = sitk.Euler2DTransform()\n",
    "# Why do we set the center?\n",
    "euler2d.SetCenter(\n",
    "    logo.TransformContinuousIndexToPhysicalPoint(np.array(logo.GetSize()) / 2.0)\n",
    ")\n",
    "\n",
    "tx = 64\n",
    "ty = 32\n",
    "euler2d.SetTranslation((tx, ty))\n",
    "\n",
    "extreme_points = [\n",
    "    logo.TransformIndexToPhysicalPoint((0, 0)),\n",
    "    logo.TransformIndexToPhysicalPoint((logo.GetWidth(), 0)),\n",
    "    logo.TransformIndexToPhysicalPoint((logo.GetWidth(), logo.GetHeight())),\n",
    "    logo.TransformIndexToPhysicalPoint((0, logo.GetHeight())),\n",
    "]\n",
    "inv_euler2d = euler2d.GetInverse()\n",
    "\n",
    "extreme_points_transformed = [inv_euler2d.TransformPoint(pnt) for pnt in extreme_points]\n",
    "min_x = min(extreme_points_transformed)[0]\n",
    "min_y = min(extreme_points_transformed, key=lambda p: p[1])[1]\n",
    "max_x = max(extreme_points_transformed)[0]\n",
    "max_y = max(extreme_points_transformed, key=lambda p: p[1])[1]\n",
    "\n",
    "# Use the original spacing (arbitrary decision).\n",
    "output_spacing = logo.GetSpacing()\n",
    "# Identity cosine matrix (arbitrary decision).\n",
    "output_direction = [1.0, 0.0, 0.0, 1.0]\n",
    "# Minimal x,y coordinates are the new origin.\n",
    "output_origin = [min_x, min_y]\n",
    "# Compute grid size based on the physical size and spacing.\n",
    "output_size = [\n",
    "    int((max_x - min_x) / output_spacing[0]),\n",
    "    int((max_y - min_y) / output_spacing[1]),\n",
    "]\n",
    "\n",
    "resampled_image = sitk.Resample(\n",
    "    logo,\n",
    "    output_size,\n",
    "    euler2d,\n",
    "    sitk.sitkLinear,\n",
    "    output_origin,\n",
    "    output_spacing,\n",
    "    output_direction,\n",
    ")\n",
    "plt.imshow(sitk.GetArrayViewFromImage(resampled_image))\n",
    "plt.axis(\"off\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Are you puzzled by the result? Is the output just a copy of the input? Add a rotation to the code above and see what happens (```euler2d.SetAngle(0.79)```)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Resampling at a set of locations \n",
    "\n",
    "In some cases you may be interested in obtaining the intensity values at a set of points (e.g. coloring the vertices of a mesh model segmented from an image).\n",
    "\n",
    "The code below generates a random point set in the image and resamples the intensity values at these locations. It is written so that it works for all image-dimensions and types (scalar or vector pixels)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img = logo\n",
    "\n",
    "# Generate random samples inside the image, we will obtain the intensity/color values at these points.\n",
    "num_samples = 10\n",
    "physical_points = []\n",
    "for pnt in zip(\n",
    "    *[list(np.random.random(num_samples) * (sz - 1)) for sz in img.GetSize()]\n",
    "):\n",
    "    physical_points.append(img.TransformContinuousIndexToPhysicalPoint(pnt))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Image based approach\n",
    "\n",
    "SimpleITK images have two methods for obtaining values at arbitrary locations `EvaluateAtPhysicalPoint` and `EvaluateAtContinuousIndex`. As these functions perform interpolation it is important to use an appropriate interpolator. For example, when working with label images we most often do not want to introduce non-label values, which leads us to use the sitkNearestNeighbor interpolator.\n",
    "\n",
    "Using points outside the image bounds will result in an exception."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "resampled_values = [None] * len(physical_points)\n",
    "for i, pnt in enumerate(physical_points):\n",
    "    resampled_values[i] = img.EvaluateAtPhysicalPoint(pnt, sitk.sitkLinear)\n",
    "# Print the interpolated values per point\n",
    "for i in range(len(physical_points)):\n",
    "    print(str(physical_points[i]) + \": \" + str(resampled_values[i]) + \"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Image Resample Filter based approach\n",
    "\n",
    "We can formulate the same task using the image resampling filter. This approach is slower than the direct approach and will also accept points outside the image bounds, in which case the `default_output_pixel_value` is used (see code below)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# Create an image of size [num_samples,1...1], actual size is dependent on the image dimensionality. The pixel\n",
    "# type is irrelevant, as the image is just defining the interpolation grid (sitkUInt8 has minimal memory footprint).\n",
    "interp_grid_img = sitk.Image(\n",
    "    [num_samples] + [1] * (img.GetDimension() - 1), sitk.sitkUInt8\n",
    ")\n",
    "\n",
    "# Define the displacement field transformation, maps the points in the interp_grid_img to the points in the actual\n",
    "# image.\n",
    "displacement_img = sitk.Image(\n",
    "    [num_samples] + [1] * (img.GetDimension() - 1),\n",
    "    sitk.sitkVectorFloat64,\n",
    "    img.GetDimension(),\n",
    ")\n",
    "for i, pnt in enumerate(physical_points):\n",
    "    displacement_img[[i] + [0] * (img.GetDimension() - 1)] = np.array(pnt) - np.array(\n",
    "        interp_grid_img.TransformIndexToPhysicalPoint(\n",
    "            [i] + [0] * (img.GetDimension() - 1)\n",
    "        )\n",
    "    )\n",
    "\n",
    "# Actually perform the resampling. The only relevant choice here is the interpolator. The default_output_pixel_value\n",
    "# is set to 0.0, but the resampling should never use it because we expect all points to be inside the image and this\n",
    "# value is only used if the point is outside the image extent.\n",
    "interpolator_enum = sitk.sitkLinear\n",
    "default_output_pixel_value = 0.0\n",
    "output_pixel_type = (\n",
    "    sitk.sitkFloat32\n",
    "    if img.GetNumberOfComponentsPerPixel() == 1\n",
    "    else sitk.sitkVectorFloat32\n",
    ")\n",
    "resampled_values = sitk.Resample(\n",
    "    img,\n",
    "    interp_grid_img,\n",
    "    sitk.DisplacementFieldTransform(displacement_img),\n",
    "    interpolator_enum,\n",
    "    default_output_pixel_value,\n",
    "    output_pixel_type,\n",
    ")\n",
    "\n",
    "# Print the interpolated values per point\n",
    "for i in range(resampled_values.GetWidth()):\n",
    "    print(\n",
    "        str(physical_points[i])\n",
    "        + \": \"\n",
    "        + str(resampled_values[[i] + [0] * (img.GetDimension() - 1)])\n",
    "        + \"\\n\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Obtaining an intensity profile along arbitrary segment \n",
    "\n",
    "In the next two cells we compute intensity profiles along arbitrary user defined segments using the image based interpolation approach.\n",
    "\n",
    "Using the GUI below, click on a location and that defines one endpoint. The next point you click on is the second endpoint for that segment. You can define as many segments as you want. Endpoints do not need to be on the same slice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Temporarily change the matplotlib back-end to enable mouse interaction\n",
    "%matplotlib widget\n",
    "intensity_profiles_image = sitk.ReadImage(fdata(\"training_001_ct.mha\"))\n",
    "point_gui = gui.PointDataAquisition(image=intensity_profiles_image);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "endpoints = point_gui.get_points()\n",
    "num_points = len(endpoints)\n",
    "# We need at least two points to define a single segment and the number of endpoints should be even\n",
    "if num_points < 2 or num_points % 2 != 0:\n",
    "    print(\n",
    "        \"At least two points required and the number of points is expected to be even.\"\n",
    "    )\n",
    "else:\n",
    "    # Change the matplotlib back-end back to inline\n",
    "    %matplotlib inline\n",
    "    # Spacing in mm, change it to a value which makes sense for your application\n",
    "    spacing = np.min(intensity_profiles_image.GetSpacing())\n",
    "    segment_data = []\n",
    "    # Iterate over the segments, interpolate values and plot\n",
    "    # (list is short so not bothering with itertools.pairwise())\n",
    "    for i in range(0, num_points - 1, 2):\n",
    "        endpoint0 = np.array(endpoints[i])\n",
    "        endpoint1 = np.array(endpoints[i + 1])\n",
    "        segment_size = np.linalg.norm(endpoint1 - endpoint0)\n",
    "        segment_direction = (endpoint1 - endpoint0) / segment_size\n",
    "        # Always include second endpoint (it won't necessarily have the same spacing as the other points).\n",
    "        x_vals = list(np.arange(0, segment_size, spacing)) + [segment_size]\n",
    "        segment_data.append(\n",
    "            (\n",
    "                x_vals,\n",
    "                [\n",
    "                    intensity_profiles_image.EvaluateAtPhysicalPoint(\n",
    "                        endpoint0 + segment_direction * x, sitk.sitkLinear\n",
    "                    )\n",
    "                    for x in x_vals\n",
    "                ],\n",
    "            )\n",
    "        )\n",
    "    plt.xlabel(\"location on segment (mm)\")\n",
    "    plt.ylabel(\"intensity\")\n",
    "    for x, y in segment_data:\n",
    "        plt.plot(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <font color=\"red\">Homework:</font> creating a color mesh\n",
    "\n",
    "You will now use the code for resampling at arbitrary locations to create a colored mesh.\n",
    "\n",
    "Using the color image of the [visible human](https://en.wikipedia.org/wiki/Visible_Human_Project) head [`img = sitk.ReadImage(fdata('vm_head_rgb.mha'))`]:\n",
    "1. Implement the [marching cubes algorithm](https://en.wikipedia.org/wiki/Marching_cubes) to obtain the set of triangles corresponding to the iso-surface of structures of interest (skin, white matter,...).\n",
    "2. Find the color associated with each of the triangle vertices using the code above.\n",
    "3. Save the data using the ASCII version of the [PLY](https://en.wikipedia.org/wiki/PLY_(file_format)), Polygon File Format (a.k.a. Stanford Triangle Format).\n",
    "4. Use [meshlab](http://www.meshlab.net/) to view your creation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Creating thumbnails - changing image size, spacing and intensity range\n",
    "\n",
    "As bio-medical images are most often an-isotropic, have a non uniform size (number of pixels), with a high dynamic range of intensities, some caution is required when converting them to an arbitrary desired size with isotropic spacing and the more common low dynamic intensity range.\n",
    "\n",
    "The code in the following cells illustrates how to take an arbitrary set of images with various sizes, spacings and intensities and resize all of them to a common arbitrary size, isotropic spacing, and low dynamic intensity range. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "file_names = [\"cxr.dcm\", \"photo.dcm\", \"POPI/meta/00-P.mhd\", \"training_001_ct.mha\"]\n",
    "images = []\n",
    "image_file_reader = sitk.ImageFileReader()\n",
    "for fname in file_names:\n",
    "    image_file_reader.SetFileName(fdata(fname))\n",
    "    image_file_reader.ReadImageInformation()\n",
    "    image_size = list(image_file_reader.GetSize())\n",
    "    # 2D image posing as a 3D one\n",
    "    if len(image_size) == 3 and image_size[2] == 1:\n",
    "        image_size[2] = 0\n",
    "        image_file_reader.SetExtractSize(image_size)\n",
    "        images.append(image_file_reader.Execute())\n",
    "    # 2D image\n",
    "    elif len(image_size) == 2:\n",
    "        images.append(image_file_reader.Execute())\n",
    "    # 3D image grab middle x-z slice\n",
    "    elif len(image_size) == 3:\n",
    "        start_index = [0, image_size[1] // 2, 0]\n",
    "        image_size[1] = 0\n",
    "        image_file_reader.SetExtractSize(image_size)\n",
    "        image_file_reader.SetExtractIndex(start_index)\n",
    "        images.append(image_file_reader.Execute())\n",
    "    # 4/5D image\n",
    "    else:\n",
    "        raise ValueError(f\"{image.GetDimension()}D image not supported.\")\n",
    "\n",
    "# Notice that in the display the coronal slices are flipped. As we are\n",
    "# using matplotlib for display, it is not aware of radiological conventions\n",
    "# and treats the image as an isotropic array of pixels.\n",
    "gui.multi_image_display2D(images);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <font color=\"red\">Homework:</font> Why do some of the images displayed above look different from others?\n",
    "\n",
    "What are the differences between the various images in the `images` list? Write code to query them and check their intensity ranges, sizes and spacings. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The next cell illustrates how to resize all images to an arbitrary size, using isotropic spacing while maintaining the original aspect ratio."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "def resize_and_scale_uint8(image, new_size, outside_pixel_value=0):\n",
    "    \"\"\"\n",
    "    Resize the given image to the given size, with isotropic pixel spacing\n",
    "    and scale the intensities to [0,255].\n",
    "\n",
    "    Resizing retains the original aspect ratio, with the original image centered\n",
    "    in the new image. Padding is added outside the original image extent using the\n",
    "    provided value.\n",
    "\n",
    "    :param image: A SimpleITK image.\n",
    "    :param new_size: List of ints specifying the new image size.\n",
    "    :param outside_pixel_value: Value in [0,255] used for padding.\n",
    "    :return: a 2D SimpleITK image with desired size and a pixel type of sitkUInt8\n",
    "    \"\"\"\n",
    "    # Rescale intensities if scalar image with pixel type that isn't sitkUInt8.\n",
    "    # We rescale first, so that the zero padding makes sense for all original image\n",
    "    # ranges. If we resized first, a value of zero in a high dynamic range image may\n",
    "    # be somewhere in the middle of the intensity range and the outer border has a\n",
    "    # constant but arbitrary value.\n",
    "    if (\n",
    "        image.GetNumberOfComponentsPerPixel() == 1\n",
    "        and image.GetPixelID() != sitk.sitkUInt8\n",
    "    ):\n",
    "        final_image = sitk.Cast(sitk.RescaleIntensity(image), sitk.sitkUInt8)\n",
    "    else:\n",
    "        final_image = image\n",
    "    new_spacing = [\n",
    "        ((osz - 1) * ospc) / (nsz - 1)\n",
    "        for ospc, osz, nsz in zip(\n",
    "            final_image.GetSpacing(), final_image.GetSize(), new_size\n",
    "        )\n",
    "    ]\n",
    "    new_spacing = [max(new_spacing)] * final_image.GetDimension()\n",
    "    center = final_image.TransformContinuousIndexToPhysicalPoint(\n",
    "        [sz / 2.0 for sz in final_image.GetSize()]\n",
    "    )\n",
    "    new_origin = [\n",
    "        c - c_index * nspc\n",
    "        for c, c_index, nspc in zip(center, [sz / 2.0 for sz in new_size], new_spacing)\n",
    "    ]\n",
    "    final_image = sitk.Resample(\n",
    "        final_image,\n",
    "        size=new_size,\n",
    "        outputOrigin=new_origin,\n",
    "        outputSpacing=new_spacing,\n",
    "        defaultPixelValue=outside_pixel_value,\n",
    "    )\n",
    "    return final_image\n",
    "\n",
    "\n",
    "# Select the arbitrary new size\n",
    "new_size = [128, 128]\n",
    "resized_images = [resize_and_scale_uint8(image, new_size, 50) for image in images]\n",
    "gui.multi_image_display2D(resized_images, figure_size=[8, 4]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Resampling after registration\n",
    "\n",
    "The result of registration is a transformation which maps points from the fixed image coordinate system to the moving image coordinate system. Most often, we then resample the moving image onto the fixed image grid using this transformation.\n",
    "\n",
    "This implicitly assumes that the information we are interested in is contained only in the overlapping regions. In some instances, this is not the case. For example, when registration is used to align multiple images to create a composite image which has a larger physical extent. This is common in microscopy where multiple tiles are combined to create the full field of view (the interested reader is referred to the [ITKMontage module](https://github.com/InsightSoftwareConsortium/ITKMontage), not available in SimpleITK).\n",
    "\n",
    "In the cells below we illustrate how to combine the result of registration using the common approach, resampling onto the fixed image grid and onto a grid that contains all image data. The only difference between these two is the definition of the resampling grid. Thus, resampling using the same registration result can yield significantly different images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an artificial registration dataset and result.\n",
    "image = sitk.ReadImage(fdata(\"cthead1.png\"))\n",
    "fixed_image = image[80:200, 100:250]\n",
    "moving_image = image[20:150, 60:160]\n",
    "registration_result = sitk.Euler2DTransform([50, 60], -0.785, [70, 80])\n",
    "# Modify the moving image origin and direction cosine using the\n",
    "# \"registration\" transformation and then add noise to the transformation\n",
    "# mimicking registration error.\n",
    "moving_image.SetOrigin(registration_result.TransformPoint(moving_image.GetOrigin()))\n",
    "moving_image.SetDirection(registration_result.GetMatrix())\n",
    "registration_result.SetTranslation(\n",
    "    [t + np.random.random() * 5 for t in registration_result.GetTranslation()]\n",
    ")\n",
    "gui.multi_image_display2D(\n",
    "    [fixed_image, moving_image], [\"fixed image\", \"moving image\"], figure_size=[5, 4]\n",
    ");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Resample the moving image onto the fixed image grid, notice that parts of the original moving image are not included\n",
    "# because they are outside the physical region occupied by the fixed image.\n",
    "resampled_moving = sitk.Resample(moving_image, fixed_image, registration_result)\n",
    "\n",
    "# Use green/magenta color scheme, image is gray in overlap regions where the registration is aligned.\n",
    "gui.multi_image_display2D(\n",
    "    [\n",
    "        sitk.Cast(\n",
    "            sitk.Compose(fixed_image, resampled_moving, fixed_image),\n",
    "            sitk.sitkVectorUInt8,\n",
    "        )\n",
    "    ],\n",
    "    [\"combined image\"],\n",
    "    figure_size=[4, 4],\n",
    ");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute the axis aligned bounding box grid for all images. Treat all images the same way, so\n",
    "# code is concise and applicable to N images of the same dimension, 2D or 3D.\n",
    "# The choice of spacing is arbitrary and implicitly defines the size of the grid.\n",
    "images = [fixed_image, moving_image]\n",
    "transforms = [sitk.Transform(2, sitk.sitkIdentity), registration_result]\n",
    "dim = images[0].GetDimension()\n",
    "\n",
    "boundary_points = []\n",
    "for image, transform in zip(images, transforms):\n",
    "    for boundary_index in list(\n",
    "        itertools.product(*zip([0] * dim, [sz - 1 for sz in image.GetSize()]))\n",
    "    ):  # Points from the moving image(s) are mapped to the fixed coordinate system using the inverse\n",
    "        # of the registration_result.\n",
    "        boundary_points.append(\n",
    "            transform.GetInverse().TransformPoint(\n",
    "                image.TransformIndexToPhysicalPoint(boundary_index)\n",
    "            )\n",
    "        )\n",
    "max_coords = np.max(boundary_points, axis=0)\n",
    "min_coords = np.min(boundary_points, axis=0)\n",
    "\n",
    "new_origin = min_coords\n",
    "# Arbitrarily use the spacing of the first image and its pixel type,\n",
    "# change these to suite your needs.\n",
    "new_spacing = images[0].GetSpacing()\n",
    "new_pixel_type = images[0].GetPixelID()\n",
    "new_size = (((max_coords - min_coords) / new_spacing).round().astype(int)).tolist()\n",
    "new_direction = np.identity(dim).ravel()\n",
    "\n",
    "# Resample all images onto the common grid.\n",
    "resampled_images = []\n",
    "for image, transform in zip(images, transforms):\n",
    "    resampled_images.append(\n",
    "        sitk.Resample(\n",
    "            image,\n",
    "            new_size,\n",
    "            transform,\n",
    "            sitk.sitkLinear,\n",
    "            new_origin,\n",
    "            new_spacing,\n",
    "            new_direction,\n",
    "            0.0,\n",
    "            new_pixel_type,\n",
    "        )\n",
    "    )\n",
    "\n",
    "# Use green/magenta color scheme, image is gray in overlap regions where the registration is aligned\n",
    "gui.multi_image_display2D(\n",
    "    [\n",
    "        sitk.Cast(\n",
    "            sitk.Compose(resampled_images[0], resampled_images[1], resampled_images[0]),\n",
    "            sitk.sitkVectorUInt8,\n",
    "        )\n",
    "    ],\n",
    "    [\"combined image\"],\n",
    "    figure_size=[4, 4],\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Repeated Resampling - Just Say No\n",
    "\n",
    "Registration workflows that yield multiple transformations are relatively common. Many workflows use an incremental approach, starting with a transformation with a low dimensional parameter space followed by a transformation with a higher dimensional parameter space. For example, first estimating an affine transformation which is then followed by a BSpline transformation. A slightly different registration workflow that yields multiple transformations is the registration of a temporal sequence. In this context, neighboring frames are registered to each other with the goal of registering all images to a single frame. This workflow can yield long transformation sequences, K transformations that map between frame N and N+K.\n",
    "\n",
    "Once we have these multiple transformations we have two options, iterate over the transformations and repeatedly resample or compose the transformations and resample once. The first option, repeated resampling, is best avoided as it yields sub-optimal results. This is due to the bounded extent of the resampling grid and to the repeated use of interpolation. Note that once a resampling grid point is mapped outside the resampled image's physical region that intensity information is lost even if a consecutive transformation would map that point inside the image's physical region.\n",
    "\n",
    "The following code cell clearly illustrates the difference. If you think it is bit of an exaggeration, change the `num_transformations` to 2 and see that even with the minimal number of incremental transformations there is a difference between repeated resampling and transformation composing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "image_to_resample = sitk.ReadImage(fdata(\"cxr.dcm\"))[:, :, 0]\n",
    "# 20 degree rotation around the image center\n",
    "rotation2D = sitk.Euler2DTransform()\n",
    "rotation2D.SetAngle(np.pi / 9)\n",
    "rotation2D.SetCenter(\n",
    "    image_to_resample.TransformContinuousIndexToPhysicalPoint(\n",
    "        [(sz - 1) / 2 for sz in image_to_resample.GetSize()]\n",
    "    )\n",
    ")\n",
    "\n",
    "# repeat the transformation num_transforms times\n",
    "num_transforms = 10\n",
    "transformations = [rotation2D] * num_transforms\n",
    "\n",
    "incremental_resampled_image = image_to_resample\n",
    "# Follow the stack based convention used by the CompositeTransform, first in, last applied.\n",
    "for tx in reversed(transformations):\n",
    "    incremental_resampled_image = sitk.Resample(incremental_resampled_image, tx)\n",
    "\n",
    "composite_resampled_image = sitk.Resample(\n",
    "    image_to_resample, sitk.CompositeTransform(transformations)\n",
    ")\n",
    "\n",
    "gui.multi_image_display2D(\n",
    "    [image_to_resample, incremental_resampled_image, composite_resampled_image],\n",
    "    [\n",
    "        \"original image\",\n",
    "        \"incremental resampling\",\n",
    "        \"transform composition and resampling\",\n",
    "    ],\n",
    "    figure_size=[10, 4],\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Resampling label images\n",
    "\n",
    "SimpleITK offers three interpolation methods which are appropriate for resampling label images (they do not introduce label values that were not in the original label image):\n",
    "* `sitkNearestNeighbor` - significantly faster than the other options, but may result in reduced accuracy along object boundaries.  \n",
    "* `sitkLabelLinear` - use when accuracy on object boundaries is more important than speed.\n",
    "* `sitkLabelGaussian` - use when accuracy on object boundaries is more important than speed, slower than `sitkLabelLinear`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Create 2D label image, a circle at the center of the image.\n",
    "# Resampling works for any number of labels but we just create one.\n",
    "image_size = [256, 256]\n",
    "new_size_factor = 3\n",
    "label_value = 250\n",
    "segmentation = (\n",
    "    sitk.GaussianSource(\n",
    "        sitk.sitkUInt8,\n",
    "        image_size,\n",
    "        sigma=[80, 80] * dim,\n",
    "        mean=[sz / 2 for sz in image_size],\n",
    "    )\n",
    "    > 150\n",
    ") * label_value\n",
    "\n",
    "new_size = [int(round(osz * new_size_factor)) for osz in segmentation.GetSize()]\n",
    "new_spacing = [\n",
    "    ((osz - 1) * ospc) / (nsz - 1)\n",
    "    for ospc, osz, nsz in zip(\n",
    "        segmentation.GetSpacing(), segmentation.GetSize(), new_size\n",
    "    )\n",
    "]\n",
    "\n",
    "# Resample using the three interpolators and combine the results so that we view the\n",
    "# images one after the other, highlights the boundary differences\n",
    "resampled_segmentation_nn = sitk.Resample(\n",
    "    segmentation,\n",
    "    new_size,\n",
    "    sitk.Transform(),\n",
    "    sitk.sitkNearestNeighbor,\n",
    "    segmentation.GetOrigin(),\n",
    "    new_spacing,\n",
    "    segmentation.GetDirection(),\n",
    "    0,\n",
    "    segmentation.GetPixelID(),\n",
    ")\n",
    "resampled_segmentation_ll = sitk.Resample(\n",
    "    segmentation,\n",
    "    new_size,\n",
    "    sitk.Transform(),\n",
    "    sitk.sitkLabelLinear,\n",
    "    segmentation.GetOrigin(),\n",
    "    new_spacing,\n",
    "    segmentation.GetDirection(),\n",
    "    0,\n",
    "    segmentation.GetPixelID(),\n",
    ")\n",
    "resampled_segmentation_lg = sitk.Resample(\n",
    "    segmentation,\n",
    "    new_size,\n",
    "    sitk.Transform(),\n",
    "    sitk.sitkLabelGaussian,\n",
    "    segmentation.GetOrigin(),\n",
    "    new_spacing,\n",
    "    segmentation.GetDirection(),\n",
    "    0,\n",
    "    segmentation.GetPixelID(),\n",
    ")\n",
    "gui.MultiImageDisplay(\n",
    "    [\n",
    "        sitk.JoinSeries(\n",
    "            resampled_segmentation_nn,\n",
    "            resampled_segmentation_ll,\n",
    "            resampled_segmentation_lg,\n",
    "        )\n",
    "    ],\n",
    "    title_list=[\"Nearest Neighbor, Label Linear, Label Gaussian\"],\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
